package com.heritage.service;

import com.heritage.dto.request.CommentRequest;
import com.heritage.dto.response.CommentResponse;
import com.heritage.entity.Comment;
import com.heritage.entity.Heritage;
import com.heritage.entity.User;
import com.heritage.exception.ResourceNotFoundException;
import com.heritage.repository.CommentRepository;
import com.heritage.repository.HeritageRepository;
import com.heritage.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private HeritageRepository heritageRepository;

    @Autowired
    private UserRepository userRepository;

    public List<CommentResponse> getCommentsByHeritageId(Long heritageId) {
        List<Comment> comments = commentRepository.findByHeritageIdOrderByCreatedAtDesc(heritageId);
        return comments.stream()
                .map(this::convertToCommentResponse)
                .collect(Collectors.toList());
    }

    @Transactional
    public CommentResponse addComment(Long heritageId, CommentRequest commentRequest) {
        String username = getCurrentUsername();
        if (username == null) {
            throw new RuntimeException("User not authenticated");
        }
        
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found"));
        
        Heritage heritage = heritageRepository.findById(heritageId)
                .orElseThrow(() -> new ResourceNotFoundException("Heritage not found with id: " + heritageId));
        
        Comment comment = new Comment();
        comment.setContent(commentRequest.getContent());
        comment.setUser(user);
        comment.setHeritage(heritage);
        
        Comment savedComment = commentRepository.save(comment);
        return convertToCommentResponse(savedComment);
    }

    private String getCurrentUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        }
        return null;
    }

    private CommentResponse convertToCommentResponse(Comment comment) {
        CommentResponse response = new CommentResponse();
        response.setId(comment.getId());
        response.setContent(comment.getContent());
        response.setUserId(comment.getUser().getId());
        response.setUsername(comment.getUser().getUsername());
        response.setHeritageId(comment.getHeritage().getId());
        response.setCreatedAt(comment.getCreatedAt());
        return response;
    }
}
